<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page import="com.yyge.entity.Userinfo" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/5/10
  Time: 15:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>员工列表</title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">


     <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
     <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>

     <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
     <%-- <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>--%>
     <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
     <!--引入日期选择插件-->
     <script src="https://cdn.bootcdn.net/ajax/libs/smalot-bootstrap-datetimepicker/2.4.4/js/bootstrap-datetimepicker.js"></script>
     <link href="https://cdn.bootcdn.net/ajax/libs/smalot-bootstrap-datetimepicker/2.4.4/css/bootstrap-datetimepicker.css" rel="stylesheet">
     <script src="https://cdn.bootcdn.net/ajax/libs/smalot-bootstrap-datetimepicker/2.4.4/js/locales/bootstrap-datetimepicker.zh-CN.js"></script>



</head>
<body>

<!--bootstrap提供的容器类-->
<div class="container">
    <table class="table table-striped table-bordered table-hover">
        <thead>
        <tr>
            <th>ID</th>
            <th>员工姓名</th>
            <th>呢称</th>
            <th>电话</th>
            <th>入职时间</th>
            <th>状态</th>
            <th>职位</th>
            <th>所属部门</th>
            <th>操作</th>
        </tr>
        </thead>

        <tbody class="text-center">
        <a id="insert">+新增员工+</a>
        <c:forEach items="${pageInfo.list}" var="employee">
            <tr>
                <td>${employee.id}</td>
                <td>${employee.name}</td>
                <td>${employee.username}</td>
                <td>${employee.phone}</td>
                <td>
                 <input class="form_datetime form-control" type="text"
                        value="<fmt:formatDate value="${employee.entryTime}" pattern="yyyy-MM-dd"/>"
                 size="16" style="display: none;text-align: center;">
                 <%--  <div id="calendar-container"></div>--%>
                 <span class="formatDate"><fmt:formatDate value="${employee.entryTime}" pattern="yyyy-MM-dd"/></span>

                </td>
                <td class="align-middle">
                    <div class="btn-group" role="dialog" >
                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" disabled="disabled" >
                               <c:if test="${employee.status==1}">正常</c:if>
                               <c:if test="${employee.status==0}">离职</c:if>
                            <span class="caret" style="display:none"></span>
                        </button>
                        <ul class="dropdown-menu" role="menu">
                            <li class="dropdown-item"><a>正常</a></li>
                            <li class="dropdown-item"><a>离职</a></li>
                        </ul>
                    </div>
               </td>
                <td>

                    <div class="btn-group" role="dialog" >
                        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" disabled="disabled" >
                                <c:if test="${employee.position==0}">负责人</c:if>
                                <c:if test="${employee.position==1}">普通员工</c:if>
                            <span class="caret" style="display:none"></span>
                        </button>
                        <ul class="dropdown-menu" role="menu">
                            <li class="dropdown-item"><a>负责人</a></li>
                            <li class="dropdown-item"><a>普通员工</a></li>
                        </ul>
                    </div>

                </td>
                <td>${employee.ofDepartment}</td>
                <td>
                   <button  type="button" onclick="this" id="btn_positive" class="btn btn-info">修改</button>
                   <button type="button" onclick="this" id="btn_negative" class="btn btn-danger">删除</button>
<%--                    <a href="delete.jsp?goodsId=${employee.id}">删除员工</a>--%>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>

    <div class="row clearfix">
        <div class="col-md-6 column">
            <ul class="pagination">
                <!--当前页不是第一页，则启用上一页按钮-->
                <c:if test="${!pageInfo.isFirstPage}">
                    <li>
                        <a href="http://localhost:8080/JavaWebTomCat/search?pageNum=${pageInfo.prePage}">上一页</a>
                    </li>
                </c:if>

                <!--如果当前页是第一页，则禁用上一页按钮-->
                <c:if test="${pageInfo.isFirstPage}">
                    <li class="disabled">
                        <a>上一页</a>
                    </li>
                </c:if>

                <c:forEach items="${pageInfo.navigatepageNums}" var="i">
                    <c:if test="${pageInfo.pageNum==i}">
                        <li class="active">
                            <a href="http://localhost:8080/JavaWebTomCat/search?pageNum=${i}">${i}</a>
                        </li>
                    </c:if>

                    <c:if test="${pageInfo.pageNum != i}">
                        <li>
                            <a href="http://localhost:8080/JavaWebTomCat/search?pageNum=${i}">${i}</a>
                        </li>
                    </c:if>

                </c:forEach>

                <!--当前页不是最后一页，则启用下一页按钮-->
                <c:if test="${!pageInfo.isLastPage}">
                    <li>
                        <a href="http://localhost:8080/JavaWebTomCat/search?pageNum=${pageInfo.nextPage}">下一页</a>
                    </li>
                </c:if>
                <!--当前页是最后一页，则禁用下一页按钮-->
                <c:if test="${pageInfo.isLastPage}">
                    <li class="disabled">
                        <a>下一页</a>
                    </li>
                </c:if>
            </ul>
        </div>

    </div>

</div>
<script type="text/javascript">
    /**
     * 日期选择器初始化函数，点击监听等
     */
    function datePickerInit(){
        $(".form_datetime").datetimepicker({
            format: "yyyy-mm-dd",
            autoclose: true,
            todayBtn: true,
            todayHighlight: true,
            showMeridian: true,
            pickerPosition: "bottom-left",
            language: 'zh-CN',//中文，需要引用zh-CN.js包
            startView: 2,//月视图
            minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
        });

        $(function () {
            // 绑定 change.dp 事件
            $('.form_datetime').on('change.dp', function (e) {
                e.target.parentElement.getElementsByClassName("formatDate")[0].innerHTML=e.target.value
                console.log(e.target.value);
            });
        });/*日期选择监听*/
    }

    datePickerInit();

    /*表格格式居中*/
    Array.from(document.getElementsByTagName("td")).map(function(x){
     x.style.verticalAlign="middle"
    })
    Array.from(document.getElementsByTagName("th")).map(function(x){
     x.style.textAlign="center"
    })

    /**
     * 批量修改按钮颜色
     */
    let autoButtonColor=function (){
        Array.from(document.querySelectorAll("button")).map(v=>{
            if(v.innerText.trim()=="正常"){v.classList.add("btn-success")}
            if(v.innerText.trim()=="离职"){v.classList.remove("btn-success")}
            if(v.innerText.trim()=="负责人"){v.classList.add("btn-warning")}
            if(v.innerText.trim()=="普通员工"){v.classList.remove("btn-warning")}
        })
    }
    autoButtonColor()//修改按钮颜色

    /*Js发送请求POST*/
    let sendPost=function (body,type){
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
          if (xhr.readyState === XMLHttpRequest.DONE) { // 当请求已完成时
            if (xhr.status === 200) { // 当状态码为 200 时
                if(type!=3) {MoDialog("提示", "员工数据修改成功！" + xhr.status,null,null,null)}
            } else {
               MoDialog("错误","员工数据修改失败！"+xhr.status,null,null,null)
              //console.error('请求失败', xhr.status);
            }
          }
        }

         xhr.open('POST',"#");
         xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
         //const data = 'name=' + encodeURIComponent('张三') + '&age=' + encodeURIComponent(18);
         xhr.send(body);
    }


    /**
     * 保存信息→传入元素本身的父类 也就是当前元素的tr
     * @param v 表示元素tr 一行的数据
     * @param type 事件类型/ 新增/修改
     */
    let preData=function (v,type){
        /*这里放需要专门设置的选项*/
        let statusNum=(v.children[5].innerText).trim()==="正常"?1:0;
        let positionNum=(v.children[6].innerText).trim()==="负责人"?0:1;
         /*type=2 根据主键修改内容*/
        let data="type="+encodeURIComponent(type)
             +"&id="+encodeURIComponent(v.children[0].innerText)
             +"&name="+encodeURIComponent(v.children[1].innerText)
             +"&username="+encodeURIComponent(v.children[2].innerText)
             +"&phone="+encodeURIComponent(v.children[3].innerText)
             +"&entryTime="+encodeURIComponent(v.children[4].innerText)
             +"&status="+encodeURIComponent(statusNum)
             +"&position="+encodeURIComponent(positionNum)
             +"&ofDepartment="+encodeURIComponent(v.children[7].innerText)
             let str="type="+type+"\n"+
                "id="+v.children[0].innerText+"\n"+
                "name="+v.children[1].innerText+"\n"+
                "username="+v.children[2].innerText+"\n"+
                "phone="+v.children[3].innerText+"\n"+
                "entryTime="+v.children[4].innerText+"\n"+
                "status="+statusNum+"\n"+
                "position="+positionNum
             console.log(str)
        if(type==3/*删除*/){v.remove();}

        sendPost(data,type)
    }

    /*判断是否有表正在被编辑*/
    let editStatus=function(){
        let statu=-1;
        Array.from(document.querySelectorAll("#btn_positive")).map(x=>{
            if(x.innerText=="保存"){
                statu=1;
                return statu;
            }
        })
        Array.from(document.querySelectorAll("#btn_positive")).map(x=>{
            if(x.innerText=="新增提交"){
                statu=1;
                return statu;
            }
        })
        console.log("编辑判定："+statu+"\n1.正在编辑..")
        return statu
    }
    /**
     * 积极按钮和消极按钮的切换状态--颜色转换
     * @param ele tr一行的元素
     * @param state1 积极状态
     * @param state2 消极状态
     */
    let buttonSwitch=function (ele,state1,state2){
        sta="btn-default";
        function assert(v){
            re=""
            re=v==0?"btn-default":re;//默认按钮
            re=v==1?"btn-primary":re;//原始按钮
            re=v==2?"btn-success":re;//成功按钮
            re=v==3?"btn-info":re;//信息按钮
            re=v==4?"btn-warning":re;//警告按钮
            re=v==5?"btn-danger":re;//危险按钮
            re=v==6?"btn-link":re;//链接按钮
            return re
        }
        state1=assert(state1)
        state2=assert(state2)

      positive=ele.querySelector("#btn_positive").classList
      negative=ele.querySelector("#btn_negative").classList
          /*判断所有状态lass 只留下 btn*/
       Array.from(positive).map(m=>{if(m!="btn"){positive.remove(m)}})
       Array.from(negative).map(m=>{if(m!="btn"){negative.remove(m)}})
        console.log(state1,state2)
       positive.add(state1)
       negative.add(state2)
    }

    /**
     * 点击编辑时修改的内容
     * type=true为用户点击按钮后开始编辑
     */
    let modifyBody=function (ele,type){
        if(type){
          ele.style.color="#3abf38"//修改字体颜色
          ele.style.fontWeight="bold"//修改字体加粗
            //console.log(ele.querySelector("#btn_positive"))
           buttonSwitch(ele,2,0)//设置积极和消极按钮颜色
           ele.querySelector("#btn_negative").innerHTML="取消"
          //隐藏原有控件
          ele.getElementsByClassName("formatDate")[0].style.display="none"
          //显示日期选择控件
          ele.getElementsByClassName("form_datetime form-control")[0].style.display="inline-block"
        }else{
          ele.style.color="unset"//修改字体颜色
          ele.style.fontWeight="unset"//修改字体加粗
          let selectInput=ele.getElementsByClassName("form_datetime form-control")[0]
          let eleSpan=ele.getElementsByClassName("formatDate")[0]
          selectInput.style.display="none"//隐藏日期选择控件
          eleSpan.style.display="inline-block"//显示原有控件
        }

     }

    /**
     * 点击button-修改信息按钮点击事件的函数-方便后续新增调用
     * 传入元素
     * */
    function buttonEvent(y) {
        /**
         * 编辑模式 从关到开
         * @param str 末尾是修改的按钮名称
         * @param y 传入的元素
         */
        function open(str,y){
            let tr = y.parentElement.parentElement
            modifyBody(tr, true);//更改样式

            Array.from(tr.children).filter((x, index, arr) => {
                return index != arr.length - 1 && index!=0;/*屏蔽第一条的ID编辑和最后一条的编辑按钮*/
            }).map(q => {
                let emeButt = q.getElementsByTagName("button")[0];
                if (emeButt) {
                    emeButt.removeAttribute("disabled")//设置点击下拉
                    let ico = emeButt.getElementsByClassName("caret")[0];
                    if (ico) {ico.style.display = "inline-block"}//显示点击下拉的图标
                } else {
                    q.contentEditable = true;/*修改为可编辑Jsp*/
                }
            })
            y.innerHTML = str
        }

        /**
         * 编辑模式 从开到关
         * @param str 末尾是修改的按钮名称
         * @param y 传入的元素
         * @param type 事件类型--新增&修改&删除...
         */
        function close(str,y,type) {
            let tr = y.parentElement.parentElement
            buttonSwitch(tr,3,5);//修改按钮颜色
            tr.querySelector("#btn_negative").innerText="删除";
            modifyBody(tr, false);//更改样式
            preData(y.parentElement.parentElement,type)//发送post

            Array.from(tr.children).filter((x, index, arr) => {
                return index != arr.length - 1
             }).map(q => {
                let emeButt = q.getElementsByTagName("button")[0];
                if (emeButt) {
                    emeButt.setAttribute("disabled", "disabled")//禁止点击下拉
                    let ico = emeButt.getElementsByClassName("caret")[0];
                    if (ico) {
                        ico.style.display = "none"
                    }//隐藏点击下拉的图标
                } else {
                    q.contentEditable = false;/*修改为不可编辑*/
                }
                autoButtonColor()//修改按钮颜色
            })
            y.innerHTML = str
        }
        switch (y.innerText) {
           case "修改" :
               if(editStatus() == -1){open("保存",y)};break;
           case "保存":
               close("修改",y,2);
               break;
           case "新增":
               if(editStatus() == -1){open("新增提交",y)};break;
           case "新增提交":
               close("修改",y,1);
               y.classList.remove("btn-success");
               y.classList.add("btn-info");
               y.nextElementSibling.style.display="unset";
               break;
            case "删除":
                let tr = y.parentElement.parentElement
                MoDialog("警告","确定要删除 "+tr.children[2].innerHTML+" 的信息吗？","删除",deleteTr,tr)
                break;
           default:
               console.log("未知判断错误！y.innerText="+y.innerText)
               break;
       }
    }

    /*遍历所有修改按钮 并添加点击事件*/
    Array.from(document.querySelectorAll(".btn")).map(x=>{
      x.addEventListener("click",y=>{
        buttonEvent(y.target)
      })
    })

    /**
     * 为所有的下拉选项框设置点击事件并将内容设置到button 的innerHTML
     */
    let setDropdown=function (){
     Array.from(document.querySelectorAll(".btn-group .dropdown-item")).map(m=>{
         m.addEventListener("click",q=>{
           q.target.parentElement.parentElement.parentElement.children[0].innerHTML=
           q.target.innerHTML +`<span class="caret" style="display: inline-block;"></span>`
           autoButtonColor()//修改按钮颜色
         })
     })
    }

    setDropdown()/*设置按钮事件*/
    /**
     * 调用弹出拟态对话框
     * @param title 对话框标题
     * @param info1 对话框信息
     * @param posBtnIofo 对话框积极按钮内容
     * @param posEve 对话框积极按钮事件
     * @param spare 备用素材传入 例如元素
     * @constructor
     */
    MoDialog=function (title,info1,posBtnIofo,posEve,spare){
        var ModalAr = document.createElement("div");
        ModalAr.classList.add("modal");
        ModalAr.classList.add("fade");
        ModalAr.setAttribute("id","exampleModal");
        ModalAr.setAttribute("tabindex","-1")
        ModalAr.setAttribute("role","dialog")
        ModalAr.setAttribute("aria-labelledby","exampleModalLabel")
        ModalAr.setAttribute("aria-hidden","true")
        ModalAr.innerHTML=`
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel" style="float: left;font-size: 2.0rem;font-weight: 600;">`+title+`</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="float: right;">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
            `+info1+`
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>
            </div>
          </div>
        </div>
        `
        if(!document.getElementById("exampleModal")){
          document.getElementsByClassName("container")[0].insertAdjacentElement("afterbegin", ModalAr)
            if(posBtnIofo=="删除"){
              pos=document.querySelector(".modal-footer>.btn.btn-primary").addEventListener("click",v=>{
                posEve(spare)
              })
            }
        }else{
            document.getElementById("exampleModalLabel").innerHTML=title;
            document.getElementsByClassName("modal-body")[0].innerHTML=info1;
        }
       $("#exampleModal").modal('show')


    }

    /**
     * 为新增员工按钮 id=insert 的设置点击事件
     */
    function inertTr(){
        document.querySelector("#insert").addEventListener("click",v=>{
            /*获取tbody 插入一行*/
            tbody=document.getElementsByClassName("text-center")[0]
            cln=tbody.children[tbody.children.length-1]//克隆元素的对象
            cln.parentElement.appendChild(cln.cloneNode(true));

            inertEle=tbody.children[tbody.children.length-1]//克隆之后的最后一个元素对象
            inertEle.addEventListener("click",e=>{
                buttonEvent(e.target)
            })

            Array.from(inertEle.children).map(e=>{
                button=e.getElementsByTagName("button")
                if(!button[0] && !e.getElementsByTagName("input")[0]){
                    e.innerText="编辑"
                }else{
                    if(button.length>1){
                        //console.log(button)
                        /*删除第二个按钮将第一个按钮内容设置位 提交新增 btn-success*/
                        button[0].innerText="新增";
                        button[0].classList.remove("btn-info")
                        button[0].classList.add("btn-success")
                        button[1].style.display="none";
                    }
                }
            })
            inertEle.children[0].innerText="*"//将ID(主键)列设置为默认*
            inertEle.children[7].innerText="1"//将部门列 设置为默认 1*

            btnList=document.getElementsByClassName("btn btn-success")/*只针对绿色按钮*/
            console.log(btnList[btnList.length-1])

            // 模拟点击
            let clickEvent = new MouseEvent("click", {view: window, bubbles: true, cancelable: true});
            btnList[btnList.length-1].dispatchEvent(clickEvent);
            btnList[btnList.length-1].innerText="新增提交";
            datePickerInit()//再次初始化日期选择器

            /*给新增的元素添加下拉点击监听*/
             Array.from(tbody.querySelectorAll(".btn-group .dropdown-item")).map(m=>{
                 m.addEventListener("click",q=>{
                   q.target.parentElement.parentElement.parentElement.children[0].innerHTML=
                   q.target.innerHTML +`<span class="caret" style="display: inline-block;"></span>`
                   autoButtonColor()//修改按钮颜色
                 })
             })
        })
    }

    inertTr();

    function deleteTr(tr){
      console.log("正在执行删除！！")
      preData(tr,3);
    }
</script>
</body>
</html>
